
package centroderecepcion;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.security.Key;
import java.security.MessageDigest;
import java.util.Vector;
import javax.crypto.Cipher;
import javax.crypto.SealedObject;
import shared.ElemConteo;
import shared.Voto;

class ConexionCliente implements Runnable {
    private Socket client;
    private PrintWriter out = null;
    private InputStream is = null;
    private ObjectInputStream ois = null;
    private BufferedReader in = null;
    private CentroDeRecepcion centro= null;

    ConexionCliente(Socket client,CentroDeRecepcion padre) {
        this.centro = padre;
        this.client = client;
        try {
            is = client.getInputStream();  
            ois = new ObjectInputStream(is);  
            out = new PrintWriter(client.getOutputStream(), true);
            in = new BufferedReader(new InputStreamReader(client.getInputStream())); 
        } catch (Exception e) {
            System.err.println(e);
            return;
        }
    }
    
    public String generateMD5(String aEnviar){
        byte[] aEncriptar = aEnviar.getBytes();
        MessageDigest algorithm;
        try {
            algorithm = MessageDigest.getInstance("MD5");
            algorithm.reset();
            algorithm.update(aEncriptar);
            byte messageDigest[] = algorithm.digest();
            StringBuffer hexString = new StringBuffer();
            for (int i=0;i<messageDigest.length;i++) {
                hexString.append(Integer.toHexString(0xFF & messageDigest[i]));
            }
            return hexString.toString();
        } 
        catch (Exception ex) {
            System.out.println(ex.getMessage());
        }
        return null;    
    }
    

    public void run() {
        centro.actualizarEstado("Acepte a un cliente");
        try{
            //Creo el objeto para desencriptar
            Cipher dcipher = Cipher.getInstance("DES");
            dcipher.init(Cipher.DECRYPT_MODE, (Key) ois.readObject());
            
            //Obtengo el SealedObject
            SealedObject os = (SealedObject) ois.readObject();
            
            //Lo desencripto
            Vector<ElemConteo> votos = (Vector<ElemConteo>) os.getObject(dcipher);;
            if(generateMD5(votos.toString()).equals(in.readLine())){
                    centro.actualizarVotos(votos);
                    out.println("OK");
                }
                else{
                    out.println("Reenviar");
                }   
        }
        catch(Exception e){
            System.out.println(e.getMessage());
        }

    }
    


}